package com.superquan.selfstudybootmybatis.utils.httpapply;

import com.superquan.selfstudybootmybatis.consts.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author zwq
 * @description HTTP工具类
 * @date 2022/4/14
 * httpPost其实在服务端模拟浏览器向其它接口发送服务的，
 * 一般情况下和httpclient，或者jsonp联合使用，可以把它理解为浏览器就行了，
 * 里面封装了http协议的一些东西，所以要对http协议有一定的了解。
 */
@Slf4j
public class HttpUtil {

    private HttpUtil() {
    }

    /**
     * post请求
     *
     * @param url
     * @param jsonStrParams
     * @return
     */
    public static String doPost(String url, String jsonStrParams) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost；url:需要请求的url
        httpPost.setHeader(new BasicHeader("Accept", "application/json"));
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        StringEntity entity = new StringEntity(jsonStrParams, Constant.Common.CHAR_SET_UTF8);
        httpPost.setEntity(entity);//放入需要传的值
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);//发送请求 并接收返回值
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();

            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, Constant.Common.CHAR_SET_UTF8);//将返回值转为String字符串
                return jsonString;
            } else {
                System.out.println("HttpStatus=" + state);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * post请求
     *
     * @param url
     * @param jsonStrParams
     * @return
     */
    public static String doPost(String url, String jsonStrParams, String charset) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader(new BasicHeader("Accept", "application/json"));
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        StringEntity entity = new StringEntity(jsonStrParams, charset);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();

            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, charset);
                return jsonString;
            } else {
                System.out.println("HttpStatus=" + state);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 像第三方发送post请求
     * @param url 请求路径
     * @param params 请求参数
     * @return
     */
    public static String sendHttp(String url,String params){
//        log.info("开始发送请求===url:"+url);
        long beginTime = System.currentTimeMillis();
        //1.创建一个httpClients对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse httpResponse = null;
        String responseContent = null;
        //2.创建一个Http请求对象并设置请求的URL，比如GET请求就创建一个HttpGet对象，POST请求就创建一个HttpPost对象;
        HttpRequestBase request = new HttpPost(url);
//        log.info("发送Http请求方法"+request.getMethod());
        //3、如果需要可以设置请求对象的请求头参数，也可以往请求对象中添加请求参数;
        request.setHeader("Content-Type", "application/json;charset=UTF-8");
        request.setHeader("token","5ab5299b2428e954d4d9a166f8e4108e");
        request.setHeader("clientId","UC");
        request.setHeader("timestamp",beginTime+"");
        //4.往对象中添加相关参数
        try{
            ((HttpEntityEnclosingRequest) request).setEntity(
                    new StringEntity(params,
                            ContentType.create("application/json", "utf-8")));
            //5.调用HttpClient对象的execute方法执行请求;
            httpResponse = httpClient.execute(request);
            //6.获取请求响应对象和响应Entity;
            HttpEntity httpEntity = httpResponse.getEntity();
//            log.info("发送地址：" + request.getURI());
//            log.info("发送内容：" + params);
//            log.info("响应状态：" + httpResponse.getStatusLine());
            //7.从响应对象中获取响应状态，从响应Entity中获取响应内容;
            if(httpEntity!=null){
                responseContent = EntityUtils.toString(httpEntity,"UTF-8");
//                log.info("响应内容：" + responseContent);
            }
        }catch (Exception e){
            e.printStackTrace();
//            log.error(e.getMessage(),e);
        }finally {
        try {
            //8、关闭响应对象;
            if (httpResponse != null) {
                httpResponse.close();
            }
            //9、关闭HttpClient.
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
//            log.error(e.getMessage(), e);
        }
    }
    long endTime = System.currentTimeMillis();
//        log.info("该接口响应时间:   " + (endTime - beginTime));
        return responseContent;
    }
}
